use reqwest::get;
use serde_json::Value;
use std::{
    fs,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use tracing::{error, info, warn};

use crate::hot::{Ad, Gov, Hot};

//获取当前时间unix戳
pub fn get_current_timestamp() -> i64 {
    let timestamp: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(time) => time.as_secs(),
        Err(_) => 0,
    };
    timestamp as i64
}
//清除过期日志

pub async fn clean_old_logs(log_dir: &str, max_age_days: u64) {
    let max_age = Duration::from_secs(max_age_days * 24 * 60 * 60);
    let now = SystemTime::now();

    match fs::read_dir(log_dir) {
        Ok(entries) => {
            for entry in entries {
                if let Ok(entry) = entry {
                    if let Ok(metadata) = entry.metadata() {
                        if let Ok(modified) = metadata.modified() {
                            if now.duration_since(modified).unwrap_or_default() > max_age {
                                if let Err(e) = fs::remove_file(entry.path()) {
                                    warn!("Failed to remove file: {:?}", e);
                                } else {
                                    info!("Removed old log file: {:?}", entry.path());
                                }
                            }
                        }
                    }
                }
            }
        }
        Err(e) => {
            error!("Failed to read log directory: {:?}", e);
        }
    }
}

//热搜
pub async fn get_hot_webapi() -> Value {
    let err_json = r#"{"ok":0}"#;
    let request_url = "https://weibo.com/ajax/side/hotSearch";
    // let response = get(request_url).await?.text().await?;
    let response = match get(request_url).await {
        Ok(res) => match res.text().await {
            Ok(content) => content,
            Err(_) => String::from(err_json),
        },
        Err(_) => String::from(err_json),
    };
    let res = serde_json::from_str(&response);
    res.unwrap()
}
//处理web热搜
pub fn handle_res_json(v: Value) -> (Vec<Ad>, Vec<Gov>, Vec<Hot>) {
    let mut current_hot_list: Vec<Hot> = Vec::new();
    let mut current_ad_list: Vec<Ad> = Vec::new();
    let mut current_gov_list: Vec<Gov> = Vec::new();
    // #region 热搜
    if let Some(items) = v["data"]["realtime"].as_array() {
        for item in items {
            //区分广告
            if let Some(_is_ad) = item["is_ad"].as_i64() {
                let mut ad = Ad::new();
                //关键词
                if let Some(word) = item["word"].as_str() {
                    ad.key_word = String::from(word);
                }
                // 推广类型
                if let Some(ad_type) = item["ad_type"].as_str() {
                    ad.ad_type = String::from(ad_type);
                }
                if let Some(id) = item["id"].as_i64() {
                    ad.id = id;
                }
                if let Some(start_time) = item["start_time"].as_i64() {
                    ad.start_time = start_time;
                }
                if let Some(end_time) = item["end_time"].as_i64() {
                    ad.end_time = end_time;
                }

                current_ad_list.push(ad);
            } else {
                //关键词
                let mut hot = Hot::new();
                if let Some(word) = item["word"].as_str() {
                    hot.key_word = String::from(word)
                }
                //分类
                if let Some(category) = item["category"].as_str() {
                    hot.category = String::from(category);
                }
                // 上榜时间
                if let Some(intime) = item["onboard_time"].as_i64() {
                    hot.onboard_time = intime;
                }
                // 通道类型
                if let Some(channel_type) = item["channel_type"].as_str() {
                    hot.channel_type = String::from(channel_type);
                }
                // 明星名字
                if let Some(star_name) = item["star_name"].as_array() {
                    let mut names = String::new();
                    for star in star_name {
                        // print!("#{}", star.as_str().unwrap());
                        if let Some(name) = star.as_str() {
                            names.push_str("#");
                            names.push_str(name);
                        }
                    }
                    hot.star_name = names;
                }

                // 排名
                if let Some(realpos) = item["realpos"].as_i64() {
                    hot.realpos = realpos as i16;
                }
                // 热度
                if let Some(raw_hot) = item["raw_hot"].as_i64() {
                    hot.raw_hot = raw_hot;
                }
                if hot.ontop_time == 0 && hot.realpos == 1 {
                    hot.ontop_time = get_current_timestamp();
                }
                current_hot_list.push(hot);
            }
        }
    }
    // #endregion
    // #region 政务
    if let Some(govs) = v["data"]["hotgovs"].as_array() {
        for item in govs {
            let mut gov = Gov {
                stime: 0,
                key_word: String::new(),
            };
            if let Some(word) = item["word"].as_str() {
                // println!("word:{} ", word);
                gov.key_word = String::from(word);
            }
            // 进入时间
            if let Some(stime) = item["stime"].as_i64() {
                // println!("stime:{} ", stime);
                gov.stime = stime;
            }
            current_gov_list.push(gov);
        }
    }
    // #endregion
    (current_ad_list, current_gov_list, current_hot_list)
}
